package config;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import freemarker.template.TemplateHashModel;

@SuppressWarnings("all")
public class FreeMarkerConfigurerCustom extends FreeMarkerConfigurer
{
	private Properties freemarkerShareds;

	private String base;

	@Override
	public void setServletContext(ServletContext servletContext)
	{
		super.setServletContext(servletContext);
		base = servletContext.getContextPath();
	}

	protected void postProcessConfiguration(Configuration config) throws IOException, TemplateException
	{
		config.setSharedVariable("base", base);
		BeansWrapper wrapper = (BeansWrapper) config.getObjectWrapper();
		TemplateHashModel staticModels = wrapper.getStaticModels();

		Iterator it = freemarkerShareds.entrySet().iterator();
		while (it.hasNext())
		{
			Map.Entry ent = (Map.Entry) it.next();
			if (ent.getKey().toString().startsWith("G_"))
			{
				TemplateHashModel fileStatics = (TemplateHashModel) staticModels.get(ent.getValue().toString());
				config.setSharedVariable(ent.getKey().toString(), fileStatics);
			}
			else if (ent.getKey().toString().startsWith("g_"))
			{
				config.setSharedVariable(ent.getKey().toString(), ent.getValue());
			}
		}
	}

	public void setFreemarkerShareds(Properties freemarkerShareds)
	{
		this.freemarkerShareds = freemarkerShareds;
	}
}